from xml.dom import minidom
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
import wxApi,qnApi
import os,urllib2

# create our little application :)
app = Flask(__name__)

# Load default config and override config from an environment variable
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'redskin.db'),
    DEBUG=True,
    SECRET_KEY='development key',
    USERNAME='admin',
    PASSWORD='default'
))
app.config.from_envvar('REDSKIN_SETTINGS', silent=True)

def connect_db():
    """Connects to the specific database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv

def init_db():
    """Initializes the database."""
    db = get_db()
    with app.open_resource('schema.sql', mode='r') as f:
        db.cursor().executescript(f.read())
    db.commit()

@app.cli.command('initdb')
def initdb_command():
    """Creates the database tables."""
    init_db()
    print('Initialized the database.')


def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db


@app.teardown_appcontext
def close_db(error):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

@app.route("/cheer/echo", methods=['GET'])
def echo():
    echostr = request.args.get('echostr')
    return echostr

@app.route("/cheer/echo", methods=['GET','POST'])
def parsePicXml():
    #parsexml
    xml = request.stream.read()
    xmldoc = minidom.parseString(xml)
    username = xmldoc.getElementsByTagName('FromUserName')[0].firstChild.nodeValue
    picUrl = xmldoc.getElementsByTagName('PicUrl')[0].firstChild.nodeValue
    print username,picUrl

    #insert into users table
    db = get_db()
    db.execute('INSERT INTO users (user_id, pic_id) VALUES (?, ?)',
               [username, picUrl])
    db.commit()
    flash('New entry was successfully posted')

    #download file
    f = urllib2.urlopen(picUrl)
    filename=os.path.join(app.root_path,username+"."+picUrl[27:30])
    with open(filename, "wb") as code:
       code.write(f.read())

    #upload to qiniu
    qnApi.upload(filename)

    #send files
    # wechat = wxApi.getInstance()
    # result = wechat.upload_media('image', open('./pic/1.jpg'))
    # print result
    return '123123123'

if __name__ == "__main__":
    app.run()